﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Core.Validation;
using System.ComponentModel;
using Kingdee.BOS.App;
using Kingdee.BOS.Contracts;
using Kingdee.K3.BD.Contracts;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Core.Metadata;

namespace K.KDL
{
    [Description("销售发票-审核操作")]
    public class CustomInvoiceAuditOpearationPlugin : AbstractOperationServicePlugIn
    {
        const string SQL = @"/*dialect*/SELECT DISTINCT FSBILLID
                    FROM T_IV_SALESIC IV
                    INNER JOIN T_IV_SALESICENTRY IVE ON IV.FID=IVE.FID
                    INNER JOIN T_IV_SALESICENTRY_LK IVLK ON IVE.FENTRYID=IVLK.FENTRYID AND IVLK.FSTABLENAME='t_AR_receivableEntry'
                    WHERE IV.FID='{0}'";

        const string EX_SQL = @"/*dialect*/SELECT DISTINCT FSBILLID
                    FROM T_IV_SALEEXINV IV
                    INNER JOIN T_IV_SALEEXINVENTRY IVE ON IV.FID=IVE.FID
                    INNER JOIN T_IV_SALEEXINVENTRY_LK IVLK ON IVE.FENTRYID=IVLK.FENTRYID AND IVLK.FSTABLENAME='t_AR_receivableEntry'
                    WHERE IV.FID='{0}'";

        const string NO_SQL = @"/*dialect*/SELECT DISTINCT FSBILLID
                    FROM T_IV_SALESIC IV
                    INNER JOIN T_IV_SALESICENTRY IVE ON IV.FID=IVE.FID
                    INNER JOIN T_IV_SALESICENTRY_LK IVLK ON IVE.FENTRYID=IVLK.FENTRYID AND IVLK.FSTABLENAME='t_AR_receivableEntry'
                    WHERE IVLK.FSBILLID='{0}' AND IV.FID!='{1}'";

        const string NO_EX_SQL = @"/*dialect*/SELECT DISTINCT FSBILLID
                    FROM T_IV_SALEEXINV IV
                    INNER JOIN T_IV_SALEEXINVENTRY IVE ON IV.FID=IVE.FID
                    INNER JOIN T_IV_SALEEXINVENTRY_LK IVLK ON IVE.FENTRYID=IVLK.FENTRYID AND IVLK.FSTABLENAME='t_AR_receivableEntry'
                    WHERE IVLK.FSBILLID='{0}' AND IV.FID!='{1}'";

        FormMetadata _arMeta;

        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            //e.FieldKeys.Add(""); 将需要应用的字段Key加入
            e.FieldKeys.Add("FINVOICEDATE");

            base.OnPreparePropertys(e);
        }

        /// <summary>
        /// 操作结束后功能处理
        /// </summary>
        /// <param name="e"></param>
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            RefreshRelatedArEndDate(e);

            base.EndOperationTransaction(e);
        }

        void RefreshRelatedArEndDate(EndOperationTransactionArgs e)
        {
            if (_arMeta == null)
            {
                _arMeta = FormMetaDataCache.GetCachedFormMetaData(Context, "AR_receivable");
            }

            var dbService = ServiceHelper.GetService<IDBService>();
            var viewService = ServiceHelper.GetService<IViewService>();
            var view = BosHelper.CreateBillView(Context, "AR_receivable");
            foreach (var entity in e.DataEntitys)
            {
                var id = entity["id"].ToString();
                var invoiceDate = (DateTime)entity["INVOICEDATE"];
                var formId = entity["FFORMID"].ToString();
                var sql = formId == "IV_SALESOC" || formId == "IV_SALESIC" ? SQL : EX_SQL; // IV_SALEEXINV, IV_SALEEXVATIN
                var relatedArList = DBUtils.ExecuteDynamicObject(Context, string.Format(sql, id));
                if (relatedArList == null || relatedArList.Count() == 0) continue;

                #region | 更新到期日计算日期 |

                foreach (var ar in relatedArList)
                {
                    var nosql = formId == "IV_SALESOC" || formId == "IV_SALESIC" ? NO_SQL : NO_EX_SQL; // IV_SALEEXINV, IV_SALEEXVATIN
                    var relatedOtherArList = DBUtils.ExecuteDynamicObject(Context, string.Format(nosql, ar["FSBILLID"], id));
                    if (relatedOtherArList != null && relatedOtherArList.Count() > 0) continue;

                    var bill = BusinessDataServiceHelper.Load(this.Context, new[] { ar["FSBILLID"] }, view.BusinessInfo.GetDynamicObjectType())?.First();
                    view.CreateNewModelData();
                    view.Model.DataObject = bill;
                    view.UpdateView();

                    //view.BusinessInfo.GetField("FACCNTTIMEJUDGETIME")?.DynamicProperty.SetValue(bill, invoiceDate);
                    view.Model.SetValue("FACCNTTIMEJUDGETIME", invoiceDate);
                    view.InvokeFieldUpdateService("FACCNTTIMEJUDGETIME", 0);

                    var operationResult = BusinessDataServiceHelper.Save(Context, _arMeta.BusinessInfo, new DynamicObject[] { bill }, null, "Save");
                    if (operationResult.IsSuccess)
                    {
                        var successEntity = operationResult.SuccessDataEnity.ToArray()[0];
                    }
                    else
                    {
                        var validationMessage = new StringBuilder();
                        foreach (var validation in operationResult.ValidationErrors)
                        {
                            validationMessage.AppendLine(validation.Message);
                        }
                        throw new InvalidOperationException($"保存更新关联应收单到期日失败：{validationMessage.ToString()}");
                    }
                }

                #endregion

            }
            view.Close();
        }
    }
}
